package com.ncr.travel.tas.testing.hamcrest.matchers;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.util.Assert.notNull;

import java.util.Iterator;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author ma250087
 * 
 */
public class HasJsonValueMatcher extends TypeSafeMatcher<JSONObject> {
	private Matcher<Object> valueMatcher;
	private Matcher<String> keyMatcher;

	public HasJsonValueMatcher(Matcher<String> keyMatcher, Matcher<Object> valueMatcher) {
		super();
		this.keyMatcher = keyMatcher;
		this.valueMatcher = valueMatcher;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean matchesSafely(JSONObject item) {
		Iterator<String> iterator = item.keys();
		while (iterator.hasNext()) {
			String next = iterator.next();
			if (keyMatcher.matches(next)) {
				Object value = null;
				try {
					value = item.get(next);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (valueMatcher.matches(value)) {
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public void describeTo(Description description) {
		description.appendText("hasValue that matches: ");
		valueMatcher.describeTo(description);
	}

	public static Matcher<JSONObject> hasJsonValue(Matcher<String> keyMatcher, Object value) {
		notNull(value, "Cannot initialize with a NULL matcher");
		return new HasJsonValueMatcher(keyMatcher, equalTo(value));
	}
}
